import { useState, useEffect } from 'react';
import { Modal, Form, Input, InputNumber, Select, message, Radio } from 'antd';
import useCouponsStore from '../../store/coupons/useCouponsStore';

const { Option } = Select;

const CouponDetail = ({ visible, onClose, coupon }) => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  
  const { createCoupon, updateCoupon } = useCouponsStore();

  useEffect(() => {
    if (visible) {
      if (coupon) {
        form.setFieldsValue(coupon);
      } else {
        form.resetFields();
        // 设置默认值
        form.setFieldsValue({
          status: 'active',
          discountRate: 10,
          validDays: 7
        });
      }
    }
  }, [visible, coupon, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);

      if (coupon) {
        await updateCoupon(coupon.id, values);
        message.success('更新成功');
      } else {
        await createCoupon(values);
        message.success('添加成功');
      }
      
      onClose();
    } catch (error) {
      console.error('提交失败:', error);
      message.error('操作失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const generateSlug = (name) => {
    return name
      .toLowerCase()
      .replace(/[\u4e00-\u9fa5]/g, '') // 移除中文字符
      .replace(/[^a-z0-9]+/g, '-') // 替换非字母数字为连字符
      .replace(/^-+|-+$/g, '') // 移除开头和结尾的连字符
      .slice(0, 50); // 限制长度
  };

  const handleNameChange = (e) => {
    const name = e.target.value;
    if (!coupon && name) {
      const slug = generateSlug(name);
      form.setFieldValue('slug', slug);
    }
  };

  const commonValidDays = [
    { label: '3天', value: 3 },
    { label: '7天', value: 7 },
    { label: '14天', value: 14 },
    { label: '30天', value: 30 },
    { label: '60天', value: 60 },
    { label: '90天', value: 90 },
    { label: '180天', value: 180 },
    { label: '365天', value: 365 },
  ];

  const commonDiscounts = [
    { label: '95折', value: 5 },
    { label: '9折', value: 10 },
    { label: '85折', value: 15 },
    { label: '8折', value: 20 },
    { label: '75折', value: 25 },
    { label: '7折', value: 30 },
    { label: '6折', value: 40 },
    { label: '5折', value: 50 },
  ];

  return (
    <Modal
      title={coupon ? '编辑优惠券' : '新增优惠券'}
      open={visible}
      onOk={handleSubmit}
      onCancel={onClose}
      width={600}
      confirmLoading={loading}
      okText="确定"
      cancelText="取消"
    >
      <Form
        form={form}
        layout="vertical"
        style={{ marginTop: 20 }}
      >
        <Form.Item
          name="name"
          label="优惠券名称"
          rules={[
            { required: true, message: '请输入优惠券名称' },
            { max: 50, message: '名称最多50个字符' }
          ]}
        >
          <Input 
            placeholder="请输入优惠券名称" 
            maxLength={50}
            onChange={handleNameChange}
            showCount
          />
        </Form.Item>

        <Form.Item
          name="slug"
          label="Slug"
          rules={[
            { required: true, message: '请输入Slug' },
            { pattern: /^[a-z0-9-]+$/, message: 'Slug只能包含小写字母、数字和连字符' },
            { max: 50, message: 'Slug最多50个字符' }
          ]}
        >
          <Input 
            placeholder="例如: new-user-discount" 
            maxLength={50}
            showCount
          />
        </Form.Item>

        <Form.Item
          label="折扣比例"
          required
        >
          <Form.Item
            name="discountRate"
            rules={[
              { required: true, message: '请输入折扣比例' },
              { type: 'number', min: 1, max: 99, message: '折扣比例必须在1-99之间' }
            ]}
            noStyle
          >
            <InputNumber
              min={1}
              max={99}
              style={{ width: '100%' }}
              placeholder="请输入折扣比例"
              formatter={value => `${value}%`}
              parser={value => value.replace('%', '')}
              addonAfter="%OFF"
            />
          </Form.Item>
          <div style={{ marginTop: 8 }}>
            <Radio.Group
              size="small"
              onChange={(e) => form.setFieldValue('discountRate', e.target.value)}
            >
              {commonDiscounts.map(item => (
                <Radio.Button key={item.value} value={item.value}>
                  {item.label}
                </Radio.Button>
              ))}
            </Radio.Group>
          </div>
        </Form.Item>

        <Form.Item
          label="有效时长"
          required
        >
          <Form.Item
            name="validDays"
            rules={[
              { required: true, message: '请输入有效时长' },
              { type: 'number', min: 1, max: 365, message: '有效时长必须在1-365天之间' }
            ]}
            noStyle
          >
            <InputNumber
              min={1}
              max={365}
              style={{ width: '100%' }}
              placeholder="请输入有效天数"
              addonAfter="天"
            />
          </Form.Item>
          <div style={{ marginTop: 8 }}>
            <Radio.Group
              size="small"
              onChange={(e) => form.setFieldValue('validDays', e.target.value)}
            >
              {commonValidDays.map(item => (
                <Radio.Button key={item.value} value={item.value}>
                  {item.label}
                </Radio.Button>
              ))}
            </Radio.Group>
          </div>
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            <Option value="active">启用</Option>
            <Option value="inactive">停用</Option>
          </Select>
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default CouponDetail;